import { Component, OnInit, HostBinding } from '@angular/core';
import { Router } from '@angular/router';

import { routerTransition } from '../shared/animation/routerTransition';
import { ToastService, PickerService } from 'ngx-weui';
import { DataStorageService } from '../data-storage.service';


import * as moment from 'moment';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.component.scss'],
  animations: [
    routerTransition
  ]
})
export class SettingComponent implements OnInit {
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display') display = 'block';
  @HostBinding('style.position') position = 'relative';

  startWork;      //上班时间
  startLunchBreak;    // 开始午休
  endLunchBreak;      //午休结束
  endWork;        // 下班

  isDoubleBreak: boolean = true;      // 是否双休


  workArr = [
    {name: 'startWork',value:''},
    {name: 'startLunchBreak',value:''},
    {name: 'endLunchBreak',value:''},
    {name: 'endWork',value:''},
  ];

  constructor(
    private router: Router,
    private srv: PickerService,
    private toast: ToastService,
    private dataStorageService: DataStorageService,
  ) { }

  ngOnInit() {
    // 初始化上班时间
    const workTime = this.dataStorageService.getLocal('workTime')? JSON.parse(this.dataStorageService.getLocal('workTime')) : null;
    if(workTime !== null){
      this.workArr.forEach(item =>{
        this[item.name] = moment(workTime[item.name])
      })
      this.isDoubleBreak = workTime.isDoubleBreak;
    }else{
      this.startWork = moment('8:00:00','HH:mm:ss');
      this.startLunchBreak = moment('12:00:00','HH:mm:ss');
      this.endLunchBreak = moment('14:00:00','HH:mm:ss');
      this.endWork = moment('17:30:00','HH:mm:ss');
      this.isDoubleBreak = false;
    }
  }


  /**
   * 保存设置的时间
   *
   * @memberof SettingComponent
   */
  setting() {
    const workTime = {};            // 所有的工作时间

    this.toast.loading('保存设置中...');
    console.log(`${this.startWork.toString()}\n${this.startLunchBreak.toString()}\n${this.endLunchBreak.toString()}\n${this.endWork.toString()}`);

    this.workArr.forEach(item => {
      item.value = this[item.name];
      workTime[item.name] = {
        time: moment(item.value).format('HH:mm:ss'),        // 这里输出为具体的时间,不携带日期
        hours: moment(item.value).hours(),
        minutes: moment(item.value).minutes(),
        seconds: moment(item.value).seconds()
      }
    });
    workTime['isDoubleBreak'] = this.isDoubleBreak;

    
    this.dataStorageService.setLocal('workTime', JSON.stringify(workTime));

    setTimeout(() => {
      this.router.navigate(['/home']);
      this.toast.hide();
    }, 1000);
  }



  /**
   *
   * 确定时间后触发的事件
   * @param {string} varName
   * @memberof SettingComponent
   */
  selectDate( varName :string) {
    this.srv.showDateTime('time').subscribe((res: any) => {
      this[varName] = res.value;
    });
  }

}
